package com.wmh.baseservice.operationaid.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wmh.baseservice.common.mybatisplus.structure.LambdaQueryWrapperX;
import com.wmh.baseservice.operationaid.convert.competitor.CompetitorConvert;
import com.wmh.baseservice.operationaid.entity.CompetitorProduct;
import com.wmh.baseservice.operationaid.mapper.CompetitorProductMapper;
import com.wmh.baseservice.operationaid.pojo.vo.competitor.ExponentialField;
import com.wmh.baseservice.operationaid.pojo.vo.competitor.RobotCommitReqVO;
import com.wmh.baseservice.operationaid.service.CompetitorProductService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 谢骏
 * @description 针对表【operation_aid_competitor_product(运营助手-竞品数据表)】的数据库操作Service实现
 * @createDate 2023-08-24 11:15:01
 */
@Service
public class CompetitorProductServiceImpl extends ServiceImpl<CompetitorProductMapper, CompetitorProduct>
        implements CompetitorProductService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void robotCommit(RobotCommitReqVO reqVO) {
        // 获取已经存在的数据主键
        Map<Long, Long> haveExistedMap = baseMapper.selectList(new LambdaQueryWrapperX<CompetitorProduct>()
                        .eq(CompetitorProduct::getDataCycle, reqVO.getDataCycle())
                        .in(CompetitorProduct::getProductId, CollUtil.map(reqVO.getExponentialFields(), ExponentialField::getProductId, true))
                        // 只需要返回主键与商品编号即可
                        .select(CompetitorProduct::getId, CompetitorProduct::getProductId))
                // 通过商品id 确认数据列表中的元素是否已经存在
                .stream().collect(Collectors.toMap(CompetitorProduct::getProductId, CompetitorProduct::getId));
        List<CompetitorProduct> entityList = CollUtil.map(reqVO.getExponentialFields(),
                item -> CompetitorConvert.INSTANCE.convert(item, haveExistedMap.get(item.getProductId()), reqVO.getDataCycle(), reqVO.getCategory())
                , true);
        saveOrUpdateBatch(entityList);
    }
}




